package com.csy.admin.web;


import com.csy.admin.entity.ResourceUrl;
import com.csy.admin.service.ResourceUrlService;
import com.csy.admin.util.PageUtils;
import com.csy.admin.util.Result;
import com.csy.common.exception.RRException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  资源目录控制类
 * </p>
 *
 * @author csy
 * @since 2018-09-17
 */
@RestController
@RequestMapping("/resourceUrl")
public class ResourceUrlController {

    @Autowired
    private ResourceUrlService resourceUrlService;

    /**
     * 获取资源url列表
     * @return
     */
    @RequestMapping(value = "/list")
    public Result list(@RequestParam Map<String,Object> map){
        PageUtils page = resourceUrlService.queryPage(map);
        return Result.ok().put("page",page);
    }

    /**
     * 根据id获取资源url信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/info/{id}",method = RequestMethod.GET)
    public Result info(@PathVariable("id") Long id){
        ResourceUrl resourceUrl = resourceUrlService.getById(id);
        return Result.ok().put("dict",resourceUrl);
    }

    /**
     * 保存资源url
     * @param resourceUrl
     * @return
     */
    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public Result save(@RequestBody ResourceUrl resourceUrl){
        resourceUrl.setFlagInvalid(0);
        resourceUrl.setCreateTime(new Date());
        verifyForm(resourceUrl);
        resourceUrlService.save(resourceUrl);
        return Result.ok();
    }

    /**
     * 修改资源参数
     * @param resourceUrl
     * @return
     */
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public Result update(@RequestBody ResourceUrl resourceUrl){
        verifyForm(resourceUrl);
        resourceUrlService.updateById(resourceUrl);
        return Result.ok();
    }

    /**
     * 验证参数是否正确
     * @param resourceUrl
     */
    private void verifyForm(ResourceUrl resourceUrl){
        if(StringUtils.isBlank(resourceUrl.getMemo())){
            throw new RRException("描述不能为空");
        }
        if(StringUtils.isBlank(resourceUrl.getUrl())){
            throw new RRException("url不能为空");
        }
        if(resourceUrl.getClassId() == null){
            throw new RRException("请选择分类");
        }
    }

    /**
     * 删除资源url
     * @param ids
     * @return
     */
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public Result delete(@RequestBody String[] ids){
        resourceUrlService.removeByIds(Arrays.asList(ids));
        return Result.ok();
    }
}

